import { effect, track, trigger } from "./effect.js"
import { TrackOperationType, TriggerOperationType } from "./operation.js"

function formatParams(getterOrOptions) {
  let getter, setter
  if (typeof getterOrOptions === 'function') {
    getter = getterOrOptions
    setter = () => {
      console.log('没有setter这个函数')
    }
  } else {
    getter = getterOrOptions.getter
    setter = getterOrOptions.setter
  }
  return { getter, setter }
}

export function computed(getterOrOptions) {
  const { getter, setter } = formatParams(getterOrOptions)
  let value, dirty = true
  const effectFn = effect(getter, {
    lazy: true,
    scheduler() {
      dirty = true
      trigger(obj, TriggerOperationType.SET, 'value')
    }
  })

  const obj = {
    get value() {
      track(this, TrackOperationType.GET, 'value')
      if (dirty) {
        value = effectFn()
        dirty = false
      }
      return value
    }
  }

  return obj
}